package cn.sdhuijin.vms.aop;

import java.nio.CharBuffer;
import java.util.Calendar;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import cn.sdhuijin.vms.model.Car;
import cn.sdhuijin.vms.model.CarRecord;
import cn.sdhuijin.vms.model.Person;
import cn.sdhuijin.vms.model.PersonRecord;
import cn.sdhuijin.vms.sms.util.SmsUtil;
import cn.sdhuijin.vms.websocket.MyMessageInboundPool;

@Component
@Aspect
public class RecordAspect {
	@Pointcut("execution(* cn.sdhuijin.vms.dao.IPersonRecordDao.save(..))")
	public void addPersonRecord() {
	}

	@Pointcut("execution(* cn.sdhuijin.vms.dao.ICarRecordDao.save(..))")
	public void addCarRecord() {
	}

	@Around("addPersonRecord()")
	public Object personSms(ProceedingJoinPoint pjp) throws Throwable {
		PersonRecord pr = (PersonRecord) pjp.getArgs()[0];

		Object object = pjp.proceed();
		Person p = pr.getPerson();
		Boolean allow = Boolean.valueOf(true);
		if (pr.getWarn().contains("违规")) {
			allow = Boolean.valueOf(false);
			String phone = p.getMaster().getPhone();
			String msg = "违规记录：姓名：" + p.getName() + " 类型：" + pr.getWarn()
					+ " 时间："
					+ DateFormatUtils.format(pr.getDate(), "yy-MM-dd HH:mm:ss")
					+ pr.getType();
			SmsUtil.sendMessage(phone, msg);
		}
		sendWebsocket(pr.getOrganization().getName(), p.getCard().getNumber(),
				p.getName(), allow);
		return object;
	}

	@Around("addCarRecord()")
	public Object carSms(ProceedingJoinPoint pjp) throws Throwable {
		CarRecord cr = (CarRecord) pjp.getArgs()[0];
		Object object = pjp.proceed();
		Car car = cr.getCar();
		Calendar cld = Calendar.getInstance();
		Integer hour = Integer.valueOf(cld.get(11));
		if ((hour.intValue() >= 18) || (hour.intValue() < 8))
			SmsUtil.sendMessage(
					car.getMasterPhone(),
					"车辆"
							+ car.getLicense()
							+ cr.getType()
							+ "时间:"
							+ DateFormatUtils.format(cr.getDate(),
									"yy-MM-dd HH:mm:ss"));

		sendWebsocket(cr.getOrganization().getName(),
				car.getCard().getNumber(), car.getLicense());
		return object;
	}

	private void sendWebsocket(String org1, Integer card, String license) {
		String msg = "card:" + card + ",license:" + license;
		MyMessageInboundPool.sendMessage(org1, CharBuffer.wrap(msg));
	}

	private void sendWebsocket(String org1, Integer card, String name,
			Boolean allow) {
		String msg = "card:" + card + ",name:" + name + ",allow:" + allow;
		MyMessageInboundPool.sendMessage(org1, CharBuffer.wrap(msg));
	}

	public static void main(String args[]) {
		Calendar cld = Calendar.getInstance();
		cld.get(Calendar.HOUR_OF_DAY);
	}
}
